package cn.qiao.netty.test;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.pkts.buffer.Buffers;
import io.pkts.packet.sip.SipMessage;
import io.pkts.packet.sip.SipResponse;
import io.pkts.packet.sip.header.ContactHeader;
import io.pkts.packet.sip.header.SipHeader;
import io.pkts.packet.sip.header.impl.SipHeaderImpl;
import io.pkts.packet.sip.impl.ImmutableSipRequest;


import java.util.Optional;
import java.util.UUID;

public class SipServer {
    private int port;

    public SipServer(int port) {
        this.port = port;
    }

    public void run() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        public void initChannel(NioSocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new SipDecoder());
                            ch.pipeline().addLast(new SipEncoder());
                            ch.pipeline().addLast(new SimpleChannelInboundHandler<SipMessage>() {
                                @Override
                                protected void channelRead0(ChannelHandlerContext ctx, SipMessage msg) throws Exception {
                                    System.out.println("接收消息: \n"+msg);

                                    SipHeaderImpl allow = new SipHeaderImpl(Buffers.wrap("Allow"), Buffers.wrap("INVITE, ACK, BYE, CANCEL, OPTIONS, MESSAGE, INFO, UPDATE, REGISTER, REFER, NOTIFY, PUBLISH, SUBSCRIBE"));
                                    if (msg.isRegister()) {
                                        ImmutableSipRequest sipRequest = (ImmutableSipRequest) msg;
                                        Optional<SipHeader> authorization = sipRequest.getHeader(  "Authorization");
                                        if (msg.isRegister() && authorization.isPresent()){
                                            ContactHeader contactHeader = msg.getContactHeader();
                                            SipResponse.Builder build = sipRequest.createResponse(200, Buffers.wrap(""));

                                            SipResponse sipResponse = build.build();
                                            ctx.writeAndFlush(sipResponse);
                                            System.out.println("返回消息200: \n" + sipResponse);
                                        }else{
                                            SipResponse.Builder build = sipRequest.createResponse(401, Buffers.wrap(""));
                                            String value = "Digest realm=" + "\"6.0.113.135"+ "\", nonce=\"" + UUID.randomUUID() + "\", algorithm=MD5, qop=\"auth\"";
                                            SipHeaderImpl sipHeader = new SipHeaderImpl(Buffers.wrap("WWW-Authenticate"), Buffers.wrap(value));

                                            build.withHeader(sipHeader);
                                            build.withHeader(allow);
                                            SipResponse sipResponse = build.build();
                                            ctx.writeAndFlush(sipResponse);
                                            System.out.println("返回消息401: \n" + sipResponse);
                                            ctx.writeAndFlush(build);
                                        }

                                    }
                                }
                            });
                        }
                    });

            ChannelFuture f = b.bind(port).sync();
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        int port = 5062; // SIP默认端口
        new SipServer(port).run();

// 192.168.1.3:5062
        String s = "REGISTER sip:192.168.1.3:5062;transport=TCP SIP/2.0\r\n" +
                "Via: SIP/2.0/TCP 192.168.1.3:52860;branch=z9hG4bK-524287-1---ecc3aa0d3a14da29;rport\n" +
                "Max-Forwards: 70\n" +
                "Contact: <sip:1000@192.168.1.3:52860;rinstance=de8590ec1dc1d60d;transport=tcp>\n" +
                "To: <sip:1000@192.168.1.3:5062;transport=TCP>\n" +
                "From: <sip:1000@192.168.1.3:5062;transport=TCP>;tag=3d1f3e5e\n" +
                "Call-ID: Ql5xzAbiuFrobrn7Ui_ujQ..\n" +
                "CSeq: 1 REGISTER\n" +
                "Expires: 70\n" +
                "Allow: INVITE, ACK, CANCEL, BYE, NOTIFY, REFER, MESSAGE, OPTIONS, INFO, SUBSCRIBE\n" +
                "Supported: replaces, norefersub, extended-refer, timer, sec-agree, outbound, path, X-cisco-serviceuri\n" +
                "User-Agent: Z 5.6.2 v2.10.20.2\n" +
                "Allow-Events: presence, kpml, talk, as-feature-event\n" +
                "Content-Length: 0";
    }


}